home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / lib / perl5 / 5.00502 / Math / BigFloat.pm.z / BigFloat.pm
Encoding:
Perl POD Document  |  1998-10-28  |  8.4 KB  |  328 lines

  1. package Math::BigFloat;
  2.  
  3. use Math::BigInt;
  4.  
  5. use Exporter;  # just for use to be happy
  6. @ISA = (Exporter);
  7.  
  8. use overload
  9. '+'    =>    sub {new Math::BigFloat &fadd},
  10. '-'    =>    sub {new Math::BigFloat
  11.                $_[2]? fsub($_[1],${$_[0]}) : fsub(${$_[0]},$_[1])},
  12. '<=>'    =>    sub {new Math::BigFloat
  13.                $_[2]? fcmp($_[1],${$_[0]}) : fcmp(${$_[0]},$_[1])},
  14. 'cmp'    =>    sub {new Math::BigFloat
  15.                $_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
  16. '*'    =>    sub {new Math::BigFloat &fmul},
  17. '/'    =>    sub {new Math::BigFloat 
  18.                $_[2]? scalar fdiv($_[1],${$_[0]}) :
  19.              scalar fdiv(${$_[0]},$_[1])},
  20. 'neg'    =>    sub {new Math::BigFloat &fneg},
  21. 'abs'    =>    sub {new Math::BigFloat &fabs},
  22.  
  23. qw(
  24. ""    stringify
  25. 0+    numify)            # Order of arguments unsignificant
  26. ;
  27.  
  28. sub new {
  29.   my ($class) = shift;
  30.   my ($foo) = fnorm(shift);
  31.   panic("Not a number initialized to Math::BigFloat") if $foo eq "NaN";
  32.   bless \$foo, $class;
  33. }
  34. sub numify { 0 + "${$_[0]}" }    # Not needed, additional overhead
  35.                 # comparing to direct compilation based on
  36.                 # stringify
  37. sub stringify {
  38.     my $n = ${$_[0]};
  39.  
  40.     my $minus = ($n =~ s/^([+-])// && $1 eq '-');
  41.     $n =~ s/E//;
  42.  
  43.     $n =~ s/([-+]\d+)$//;
  44.  
  45.     my $e = $1;
  46.     my $ln = length($n);
  47.  
  48.     if ($e > 0) {
  49.     $n .= "0" x $e . '.';
  50.     } elsif (abs($e) < $ln) {
  51.     substr($n, $ln + $e, 0) = '.';
  52.     } else {
  53.     $n = '.' . ("0" x (abs($e) - $ln)) . $n;
  54.     }
  55.     $n = "-$n" if $minus;
  56.  
  57.     # 1 while $n =~ s/(.*\d)(\d\d\d)/$1,$2/;
  58.  
  59.     return $n;
  60. }
  61.  
  62. $div_scale = 40;
  63.  
  64. # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
  65.  
  66. $rnd_mode = 'even';
  67.  
  68. sub fadd; sub fsub; sub fmul; sub fdiv;
  69. sub fneg; sub fabs; sub fcmp;
  70. sub fround; sub ffround;
  71. sub fnorm; sub fsqrt;
  72.  
  73. # Convert a number to canonical string form.
  74. #   Takes something that looks like a number and converts it to
  75. #   the form /^[+-]\d+E[+-]\d+$/.
  76. sub fnorm { #(string) return fnum_str
  77.     local($_) = @_;
  78.     s/\s+//g;                               # strip white space
  79.     if (/^([+-]?)(\d*)(\.(\d*))?([Ee]([+-]?\d+))?$/ && "$2$4" ne '') {
  80.     &norm(($1 ? "$1$2$4" : "+$2$4"),(($4 ne '') ? $6-length($4) : $6));
  81.     } else {
  82.     'NaN';
  83.     }
  84. }
  85.  
  86. # normalize number -- for internal use
  87. sub norm { #(mantissa, exponent) return fnum_str
  88.     local($_, $exp) = @_;
  89.     if ($_ eq 'NaN') {
  90.     'NaN';
  91.     } else {
  92.     s/^([+-])0+/$1/;                        # strip leading zeros
  93.     if (length($_) == 1) {
  94.         '+0E+0';
  95.     } else {
  96.         $exp += length($1) if (s/(0+)$//);  # strip trailing zeros
  97.         sprintf("%sE%+ld", $_, $exp);
  98.     }
  99.     }
  100. }
  101.  
  102. # negation
  103. sub fneg { #(fnum_str) return fnum_str
  104.     local($_) = fnorm($_[$[]);
  105.     vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
  106.     s/^H/N/;
  107.     $_;
  108. }
  109.  
  110. # absolute value
  111. sub fabs { #(fnum_str) return fnum_str
  112.     local($_) = fnorm($_[$[]);
  113.     s/^-/+/;                               # mash sign
  114.     $_;
  115. }
  116.  
  117. # multiplication
  118. sub fmul { #(fnum_str, fnum_str) return fnum_str
  119.     local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
  120.     if ($x eq 'NaN' || $y eq 'NaN') {
  121.     'NaN';
  122.     } else {
  123.     local($xm,$xe) = split('E',$x);
  124.     local($ym,$ye) = split('E',$y);
  125.     &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
  126.     }
  127. }
  128.  
  129. # addition
  130. sub fadd { #(fnum_str, fnum_str) return fnum_str
  131.     local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
  132.     if ($x eq 'NaN' || $y eq 'NaN') {
  133.     'NaN';
  134.     } else {
  135.     local($xm,$xe) = split('E',$x);
  136.     local($ym,$ye) = split('E',$y);
  137.     ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
  138.     &norm(Math::BigInt::badd($ym,$xm.('0' x ($xe-$ye))),$ye);
  139.     }
  140. }
  141.  
  142. # subtraction
  143. sub fsub { #(fnum_str, fnum_str) return fnum_str
  144.     fadd($_[$[],fneg($_[$[+1]));    
  145. }
  146.  
  147. # division
  148. #   args are dividend, divisor, scale (optional)
  149. #   result has at most max(scale, length(dividend), length(divisor)) digits
  150. sub fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
  151. {
  152.     local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
  153.     if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
  154.     'NaN';
  155.     } else {
  156.     local($xm,$xe) = split('E',$x);
  157.     local($ym,$ye) = split('E',$y);
  158.     $scale = $div_scale if (!$scale);
  159.     $scale = length($xm)-1 if (length($xm)-1 > $scale);
  160.     $scale = length($ym)-1 if (length($ym)-1 > $scale);
  161.     $scale = $scale + length($ym) - length($xm);
  162.     &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),$ym),
  163.         $xe-$ye-$scale);
  164.     }
  165. }
  166.  
  167. # round int $q based on fraction $r/$base using $rnd_mode
  168. sub round { #(int_str, int_str, int_str) return int_str
  169.     local($q,$r,$base) = @_;
  170.     if ($q eq 'NaN' || $r eq 'NaN') {
  171.     'NaN';
  172.     } elsif ($rnd_mode eq 'trunc') {
  173.     $q;                         # just truncate
  174.     } else {
  175.     local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base);
  176.     if ( $cmp < 0 ||
  177.          ($cmp == 0 &&
  178.           ( $rnd_mode eq 'zero'                             ||
  179.            ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
  180.            ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
  181.            ($rnd_mode eq 'even' && $q =~ /[24680]$/)        ||
  182.            ($rnd_mode eq 'odd'  && $q =~ /[13579]$/)        )) ) {
  183.         $q;                     # round down
  184.     } else {
  185.         Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
  186.                     # round up
  187.     }
  188.     }
  189. }
  190.  
  191. # round the mantissa of $x to $scale digits
  192. sub fround { #(fnum_str, scale) return fnum_str
  193.     local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
  194.     if ($x eq 'NaN' || $scale <= 0) {
  195.     $x;
  196.     } else {
  197.     local($xm,$xe) = split('E',$x);
  198.     if (length($xm)-1 <= $scale) {
  199.         $x;
  200.     } else {
  201.         &norm(&round(substr($xm,$[,$scale+1),
  202.              "+0".substr($xm,$[+$scale+1,1),"+10"),
  203.           $xe+length($xm)-$scale-1);
  204.     }
  205.     }
  206. }
  207.  
  208. # round $x at the 10 to the $scale digit place
  209. sub ffround { #(fnum_str, scale) return fnum_str
  210.     local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
  211.     if ($x eq 'NaN') {
  212.     'NaN';
  213.     } else {
  214.     local($xm,$xe) = split('E',$x);
  215.     if ($xe >= $scale) {
  216.         $x;
  217.     } else {
  218.         $xe = length($xm)+$xe-$scale;
  219.         if ($xe < 1) {
  220.         '+0E+0';
  221.         } elsif ($xe == 1) {
  222.         &norm(&round('+0',"+0".substr($xm,$[+1,1),"+10"), $scale);
  223.         } else {
  224.         &norm(&round(substr($xm,$[,$xe),
  225.               "+0".substr($xm,$[+$xe,1),"+10"), $scale);
  226.         }
  227.     }
  228.     }
  229. }
  230.     
  231. # compare 2 values returns one of undef, <0, =0, >0
  232. #   returns undef if either or both input value are not numbers
  233. sub fcmp #(fnum_str, fnum_str) return cond_code
  234. {
  235.     local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
  236.     if ($x eq "NaN" || $y eq "NaN") {
  237.     undef;
  238.     } else {
  239.     ord($y) <=> ord($x)
  240.     ||
  241.     (  local($xm,$xe,$ym,$ye) = split('E', $x."E$y"),
  242.          (($xe <=> $ye) * (substr($x,$[,1).'1')
  243.              || Math::BigInt::cmp($xm,$ym))
  244.     );
  245.     }
  246. }
  247.  
  248. # square root by Newtons method.
  249. sub fsqrt { #(fnum_str[, scale]) return fnum_str
  250.     local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
  251.     if ($x eq 'NaN' || $x =~ /^-/) {
  252.     'NaN';
  253.     } elsif ($x eq '+0E+0') {
  254.     '+0E+0';
  255.     } else {
  256.     local($xm, $xe) = split('E',$x);
  257.     $scale = $div_scale if (!$scale);
  258.     $scale = length($xm)-1 if ($scale < length($xm)-1);
  259.     local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
  260.     while ($gs < 2*$scale) {
  261.         $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
  262.         $gs *= 2;
  263.     }
  264.     new Math::BigFloat &fround($guess, $scale);
  265.     }
  266. }
  267.  
  268. 1;
  269. __END__
  270.  
  271. =head1 NAME
  272.  
  273. Math::BigFloat - Arbitrary length float math package
  274.  
  275. =head1 SYNOPSIS
  276.  
  277.   use Math::BigFloat;
  278.   $f = Math::BigFloat->new($string);
  279.  
  280.   $f->fadd(NSTR) return NSTR            addition
  281.   $f->fsub(NSTR) return NSTR            subtraction
  282.   $f->fmul(NSTR) return NSTR            multiplication
  283.   $f->fdiv(NSTR[,SCALE]) returns NSTR   division to SCALE places
  284.   $f->fneg() return NSTR                negation
  285.   $f->fabs() return NSTR                absolute value
  286.   $f->fcmp(NSTR) return CODE            compare undef,<0,=0,>0
  287.   $f->fround(SCALE) return NSTR         round to SCALE digits
  288.   $f->ffround(SCALE) return NSTR        round at SCALEth place
  289.   $f->fnorm() return (NSTR)             normalize
  290.   $f->fsqrt([SCALE]) return NSTR        sqrt to SCALE places
  291.  
  292. =head1 DESCRIPTION
  293.  
  294. All basic math operations are overloaded if you declare your big
  295. floats as
  296.  
  297.     $float = new Math::BigFloat "2.123123123123123123123123123123123";
  298.  
  299. =over 2
  300.  
  301. =item number format
  302.  
  303. canonical strings have the form /[+-]\d+E[+-]\d+/ .  Input values can
  304. have inbedded whitespace.
  305.  
  306. =item Error returns 'NaN'
  307.  
  308. An input parameter was "Not a Number" or divide by zero or sqrt of
  309. negative number.
  310.  
  311. =item Division is computed to 
  312.  
  313. C<max($div_scale,length(dividend)+length(divisor))> digits by default.
  314. Also used for default sqrt scale.
  315.  
  316. =back
  317.  
  318. =head1 BUGS
  319.  
  320. The current version of this module is a preliminary version of the
  321. real thing that is currently (as of perl5.002) under development.
  322.  
  323. =head1 AUTHOR
  324.  
  325. Mark Biggar
  326.  
  327. =cut
  328.